"""
主题: 通过CIDR地址生成对应的IP地址集
问题: 你有一个CIDR网络地址比如“123.45.67.89/27”，你想将其转换成它所代表的所有IP 
提示 : 
"""

import ipaddress
from socket import socket, AF_INET, SOCK_STREAM

def recipe1():
    net = ipaddress.ip_network('123.45.67.64/27')
    print(f"{net = }")
    print(f"{net.num_addresses = }")
    print(f"{net[1] = }")
    print(f"{net[-1] = }")

    for a in net:
        print(f"{a = }")

    a = ipaddress.ip_address('123.45.67.69')
    print(f"{a in net = }")

    b = ipaddress.ip_address('123.45.67.123')
    print(f"{b in net = }")

def recipe2():
    net6 = ipaddress.ip_network('12:3456:78:90ab:cd:ef01:23:30/125')
    print(f"{net6 = }")
    for a in net6:
        print(f"{a = }")


def recipe3():
    '''一个IP地址和网络地址能通过一个IP接口来指定'''
    inet = ipaddress.ip_interface('123.45.67.73/27')
    print(f"{inet.network = }")
    print(f"{inet.ip = }")

def recipe4():
    a = ipaddress.ip_address('127.0.0.1')
    s = socket(AF_INET, SOCK_STREAM)

    s.connect((str(a), 20001))

    try:
        s.connect((a, 20001))
    except TypeError as e:
        print(e)  

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()
    print('recipe4'.center(20, '*'))
    recipe4()

if __name__ == '__main__':
    main() 